package com.lry.util.common.response;

import com.lry.util.common.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 响应拦截
 *
 * @author ALI
 * @date 2021/12/09
 */
@Slf4j
@RestControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {

    @ExceptionHandler(Exception.class)
    public ResponseData handleException(Exception e) {
        return ResponseData.builder().code(ResponseData.FAILED).message(e.getMessage()).status(false)
                           .build();
    }


    @ExceptionHandler(RuntimeException.class)
    public ResponseData handleRuntimeException(Exception e) {
        return ResponseData.builder().code(ResponseData.FAILED).message(e.getMessage()).status(false)
                           .build();
    }

    /**
     * 业务异常
     *
     * @param e 异常
     * @return 结果
     */
    @ExceptionHandler(AppException.class)
    public ResponseData AppException(Exception e) {
        return ResponseData.builder().code(ResponseData.FAILED).message(e.getMessage()).status(false).tip(true)
                           .build();
    }

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class aClass,
                                  ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (MediaType.APPLICATION_JSON.equals(mediaType) || MediaType.APPLICATION_JSON_UTF8.equals(mediaType)) {
            if (body instanceof ResponseData) {
                return body;
            } else {
                return ResponseData.builder().data(body).status(true).message("成功").code(ResponseData.SUCCESS).build();
            }

        }
        return body;
    }


}
